import OSS from "ali-oss";
import { Message } from "element-ui";

const env = {
  Bucket: "mifengcar", // 存储空间名称
  Region: "oss-cn-hangzhou",
  EndPoint: "https://mifengcar.oss-cn-hangzhou.aliyuncs.com", // 默认存在根目录，可根据需求改
  AccessKeyId: "LTAI5tH1jKmQFXTKxJSdE3QL", // AccessKeyId
  SecretKey: "6rmd9QltWlw21i7Qm1cP4EKRjo3CdN", // SecretKey
  timeout: 87600, //这个是上传文件时Policy的失效时间
  directory: "images",
};

const OssClient = new OSS({
  region: env.Region,
  bucket: env.Bucket,
  authorizationV4: true,
  accessKeyId: env.AccessKeyId,
  accessKeySecret: env.SecretKey,
});

const headers = {
  // 指定该Object被下载时的网页缓存行为。
  // "Cache-Control": "no-cache",
  // 指定该Object被下载时的名称。
  // "Content-Disposition": "example.txt",
  // 指定该Object被下载时的内容编码格式。
  // "Content-Encoding": "utf-8",
  // 指定过期时间，单位为毫秒。
  // Expires: "1000",
  // 指定Object的存储类型。
  // "x-oss-storage-class": "Standard",
  // 指定Object的访问权限。
  "x-oss-object-acl": "public-read",
  // 指定Object标签，可同时设置多个标签。
  // "x-oss-tagging": "Tag1=1&Tag2=2",
  // 指定初始化分片上传时是否覆盖同名Object。此处设置为true，表示禁止覆盖同名Object。
  "x-oss-forbid-overwrite": "true",
};

function rx() {
  return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1);
}

function getDateStr() {
  let date = new Date();
  let y = date.getFullYear();
  let month = date.getMonth() + 1;
  month = month < 10 ? "0" + month : month;
  let day = date.getDate();
  day = day < 10 ? "0" + day : day;
  let hour = date.getHours();
  hour = hour < 10 ? "0" + hour : hour;
  let minute = date.getMinutes();
  minute = minute < 10 ? "0" + minute : minute;
  let second = date.getSeconds();
  second = second < 10 ? "0" + second : second;
  return y + month + day + hour + minute + second;
}

/**
 * 生成随机uuid
 */
export const getFileNameUUID = () => {
  return getDateStr() + "_" + `${+new Date()}_${rx()}${rx()}`;
};

/**
 * 上传文件
 * @returns {Promise<unknown>|void}
 */
const uploadFile = async (file, fileName = "") => {
  console.log("uploadFile", file, fileName);
  if (!file) {
    return Message.info({ message: "请选择需要上传的文件" });
  }
  const newFileName = `${getFileNameUUID()}_${encodeURIComponent(fileName)}`;
  const fileKey = `${env.directory}/${newFileName}`;
  const res = await OssClient.put(fileKey, file, { headers });
  console.log(res);
  return {
    ...(res || {}),
    fileName: newFileName,
  };
};

export default uploadFile;
